package cn.cj.erp.service;

import cn.cj.erp.bo.system.SysDeptBo;
import cn.cj.erp.common.utils.Assert;
import cn.cj.erp.common.utils.Convert;
import cn.cj.erp.common.vo.RoleDeptVo;
import cn.cj.erp.common.vo.TreeNode;
import cn.cj.erp.service.system.SysDeptService;
import cn.cj.erp.service.system.SysRoleDeptService;
import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 部门处理
 *
 * @author jianchen
 */
@Slf4j
@Service
public class DeptService {
    @Resource
    private SysDeptService sysDeptService;
    @Resource
    private SysRoleDeptService sysRoleDeptService;

    /**
     * 加载对应角色部门列表树
     * @param roleId 角色id
     * @return 角色对应地部门树
     */
    public RoleDeptVo roleDeptTree(Long roleId) {
        Assert.notNull(roleId, "角色id不能为空");
        //查询角色对应的部门
        List<Long> deptIds = sysRoleDeptService.listDeptIdsByRoleIds(Collections.singletonList(roleId));
        // 给前端使用，需要将Long列表转化成String列表
        List<String> checkedKeys = deptIds.stream().map(Convert::toStr).collect(Collectors.toList());
        List<SysDeptBo> deptList = sysDeptService.queryTree(new SysDeptBo());
        return new RoleDeptVo(checkedKeys, deptList);
    }

    /**
     * 构建前端选择的树结构
     * @param params 参数 {level:展开层级, parentId:父节点ID}
     * @return 树形部门结构
     */
    public List<TreeNode> queryTreeNode(SysDeptBo params) {
        List<SysDeptBo> treeList = sysDeptService.queryTree(params);
        return recursionWrapTreeNode(treeList);
    }

    /**
     * 递归将实体类树 => TreeNode
     * @param list 菜单列表
     * @return 路由列表
     **/
    private List<TreeNode> recursionWrapTreeNode(List<SysDeptBo> list) {
        List<TreeNode> treeNodeList = new LinkedList<>();
        for (SysDeptBo temp : list) {
            TreeNode treeNode = new TreeNode();
            treeNode.setId(temp.getDeptId());
            treeNode.setTitle(temp.getName());
            treeNode.setParentIds(temp.getParentIds());
            if (CollectionUtil.isNotEmpty(temp.getChildren())) {
                treeNode.setChildren(recursionWrapTreeNode(temp.getChildren()));
            }
            treeNodeList.add(treeNode);
        }
        return treeNodeList;
    }
}